package com.atguigu.blog.exception;

import com.atguigu.blog.dto.response.R;
import com.atguigu.blog.dto.response.Result;
import com.atguigu.blog.exception.common.BizCodeEnume;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ConnectTimeoutException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.blog.web")
public class BlogException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValueException(MethodArgumentNotValidException e) {
        log.debug("数据校验出现问题！{}, 异常类型:{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        log.error("错误：", throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

    @ExceptionHandler(value = ConnectTimeoutException.class)
    public R connectTimeoutException(ConnectTimeoutException connectTimeoutException) {
        log.error("连接超时：", connectTimeoutException);
        return R.error(BizCodeEnume.CONNECTTIMEOUT.getCode(), BizCodeEnume.CONNECTTIMEOUT.getMsg());
    }

    @ExceptionHandler(value =  MailSendException.class)
    public Result timeoutException(MailSendException mailSendException) {
        log.error("请求超时：", mailSendException);
        return Result.error(BizCodeEnume.TIMEOUT.getCode(), BizCodeEnume.TIMEOUT.getMsg());
    }

    @ExceptionHandler(value = MessagingException.class)
    public R messagingException(MessagingException messagingException) {
        log.error("MessagingException错误：", messagingException);
        return R.error(BizCodeEnume.TIMEOUT.getCode(), BizCodeEnume.TIMEOUT.getMsg());
    }

}